import router, { constantRoutes } from "@/router";
import Layout from "@/layout";
import { getRouters } from "@/api/menu";
// 匹配views里面所有的.vue文件
const modules = import.meta.glob("./../../views/**/*.vue");

const usePermissionStore = defineStore("permission", {
  state: () => ({
    routes: [], //动态总路由
    addRoutes: [], //动态路由 添加项
    sidebarRoutes: [], //侧边栏路由
    cacheRoutes: [], //缓存路由
  }),
  actions: {
    setRoutes(routes) {
      this.addRoutes = routes;
      this.routes = constantRoutes.concat(routes);
    },
    setSidebarRouters(routes) {
      this.sidebarRoutes = routes;
    },
    setCacheRouter(routes) {
      this.cacheRoutes = routes;
    },
    generateRoutes() {
      return new Promise((resolve) => {
        // 向后端请求路由数据
        getRouters().then((res) => {
          // 独立copy data
          const sdata = JSON.parse(JSON.stringify(res.data));
          const rdata = JSON.parse(JSON.stringify(res.data));
          const cdata = JSON.parse(JSON.stringify(res.data));
          // 侧边栏菜单
          const sidebarRoutes = filterAsyncRouter(sdata);
          // 缓存菜单
          const cacheRoutes = filterCacheRoute(constantRoutes.concat(cdata));
          // 动态路由
          const rewriteRoutes = filterAsyncRouter(rdata, false, true);
          this.setRoutes(rewriteRoutes);
          this.setSidebarRouters(constantRoutes.concat(sidebarRoutes));
          this.setCacheRouter(cacheRoutes);
          resolve(rewriteRoutes);
        });
      });
    },
  },
});
function filterCacheRoute(cacheRoutes) {
  let cacheRouteName = [];
  cacheRoutes.filter((route) => {
    if (route.children) {
      cacheRouteName = cacheRouteName.concat(filterCacheRoute(route.children));
    }
    if (route.hasOwnProperty("meta") && route.meta.cache) cacheRouteName.push(route.name);
    return true;
  });
  return cacheRouteName;
}
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children);
    }
    if (route.component) {
      // component 找组件实例
      if (route.component === "Layout") {
        route.component = Layout;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type);
    } else {
      delete route["children"];
      delete route["redirect"];
    }
    return true;
  });
}

//设置路由path
function filterChildren(childrenMap, lastRouter = false) {
  var children = [];
  childrenMap.forEach((el, index) => {
    if (lastRouter) {
      el.path = lastRouter.path + "/" + el.path;
      if (el.children && el.children.length) {
        children = children.concat(filterChildren(el.children, el));
        return;
      }
    }
    children = children.concat(el);
  });
  return children;
}

// 获取路由 本地路径
export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split("views/")[1].split(".vue")[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
};

export default usePermissionStore;
